import { SocketContainer } from '@/hooks/useSocket'
import { history, useLocation } from 'umi'
import Store from './store'
import { observer, useLocalObservable } from 'mobx-react'
import { getSessionStorage, setLocalStorage } from '@/storage'
import { toJS } from 'mobx'
import { useEffect, useRef, useState } from 'react'
import btn_small_n from '@/resource/auctionManage/btn_small_n.png'
import btn_small_s from '@/resource/auctionManage/btn_small_s.png'

import styles from './index.module.less'
import useFullScreen from '@/hooks/useFullScreen'
import HoverImage from './components/HoverImg'
import IconFont from '@/components/IconFont'
import kingUrl, { kingWs } from '@/servers/kingUrl'

export default observer((props: any) => {
    const audioRef = useRef<any>(null)
    const [isPlay, setIsPlay] = useState<boolean>(false)
    const [audioSty, setAudioSty] = useState({})
    const store = useLocalObservable(() => Store)
    const { userInfo, teacherquickLogin, setUserInfo, createAuction, auction_record_id, setData, binding_info } = store
    const { uid } = userInfo
    const { isFullScreen, toggleFullScreen } = useFullScreen()
    const {
        query: { access_token, domain, side_type = 1, student_num, gid, callback_url },
    }: any = useLocation()
    const teacherInfo = getSessionStorage('TEACHER_USER_INFO')

    /** 白名单 */
    const whiteUrl = ['/auctionmanage/result']
    const isWhiteUrl = !!whiteUrl.filter(item => window.location.href.indexOf(item) > -1).length

    useEffect(() => {
        document.title = '拍卖游戏'
        setLocalStorage('CALLBACK_URL', callback_url ? decodeURIComponent(callback_url) : '')
        if (audioRef.current) {
            audioRef.current.muted = false
            setIsPlay(audioRef.current.muted ? false : true)
        }
        /** 快捷登录 */
        if (access_token && domain && gid) {
            teacherquickLogin({ access_token, domain, gid, side_type }).then(() => {
                /** 创建实训游戏 */
                if (student_num) {
                    createAuction(student_num)
                }
            })
        } else if (teacherInfo) {
            setUserInfo(teacherInfo)
            if (student_num) {
                createAuction(student_num)
            }
        }
    }, [])
    /** 音乐静音切换 */
    const playOrPause = () => {
        // 如果是暂停状态并且未播放完成
        if (audioRef.current.paused && !audioRef.current.ended) {
            audioRef.current.play().then(() => {
                audioRef.current.muted = false
                setIsPlay(true)
            })
            return
        }
        if (audioRef.current.muted) {
            audioRef.current.muted = false
            setIsPlay(true)
        } else {
            audioRef.current.muted = true
            setIsPlay(false)
        }
    }
    /**
     * 切换背景音
     * @param rateType 拍卖进度状态
     */
    const changeAudio = (rateType: string) => {
        let audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效1-开场.mp3'
        let audioLoop = false
        let style = {}
        switch (rateType) {
            case 'form':
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效1-开场.mp3'
                break
            case 'submit':
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效2-竞拍统计表阶段.mp3'
                style = { top: '16px' }
                break
            case 'info':
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效3-拍卖开始前规则解读.mp3'
                audioLoop = true
                break
            case 'game':
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效5-拍卖进行中背景音乐.mp3'
                audioLoop = true
                break
            case 'statistic':
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观拍卖会音效6-结束.mp3'
                style = { top: '16px' }
                break
            default:
                audioSrc = 'https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效1-开场.mp3'
                break
        }
        setAudioSty(style)
        audioRef.current.src = audioSrc
        audioRef.current.loop = audioLoop
        audioRef.current.play().then(() => {
            audioRef.current.muted = false
            setIsPlay(true)
        })
    }

    if (isWhiteUrl) {
        return props.children
    }

    console.log(uid)
    return uid ? (
        <div>
            <HoverImage onClick={toggleFullScreen} className={styles.full_btn} src={btn_small_s} placeholderSrc={btn_small_n}>
                {isFullScreen ? (
                    <>
                        <IconFont type="icon-icon_tuichuquanping" />
                        退出全屏
                    </>
                ) : (
                    <>
                        <IconFont type="icon-icon_jinruquanping" />
                        进入全屏
                    </>
                )}
            </HoverImage>
            {!!auction_record_id && (
                <SocketContainer.Provider
                    initialState={{
                        url: kingWs,
                        time: 10000,
                        params: {
                            channel: 'auction-game',
                            token: userInfo.access_token,
                            user_id: uid,
                            role: 'client',
                            auction_record_id,
                        },
                        init: ({ send, onMessage }) => {
                            /** 状态流转 */
                            const step_flow = ({ data }: any) => {
                                const { goto, form_statistic_arr, lot_obj, is_last_lot, bidding_student_num } = data || {}
                                changeAudio(goto)
                                let url: string = ''
                                switch (goto) {
                                    case 'form':
                                        url = `/auctionmanage?student_num=${student_num}`
                                        break
                                    case 'submit':
                                        url = `/auctionmanage/statistics?student_num=${student_num}`
                                        setData('form_statistic_arr', form_statistic_arr)
                                        break
                                    case 'info':
                                        url = `/auctionmanage/explain?student_num=${student_num}`
                                        break
                                    case 'game':
                                        url = `/auctionmanage/game?student_num=${student_num}`
                                        setData('lot_obj', { ...lot_obj, is_last_lot })
                                        setData('binding_info', {
                                            ...binding_info,
                                            bidding_student_num,
                                        })
                                        break
                                    case 'statistic':
                                        url = `/auctionmanage/result?id=${auction_record_id}`
                                        break
                                    default:
                                        break
                                }
                                const curHref = window.location.href
                                if (url && curHref.indexOf(url?.split('?')[0]) < 0) {
                                    history.replace(url)
                                }
                            }
                            onMessage('step_flow', step_flow)

                            const submit = ({ data }: any) => {
                                console.log(data)
                                setTimeout(() => {
                                    setData('form_statistic_arr', data.form_statistic_arr)
                                }, 400)
                            }
                            onMessage('submit', submit)

                            /** 建立连接 */
                            send('step_flow', { params: { step: '1' } })
                        },
                    }}
                >
                    {props.children}
                </SocketContainer.Provider>
            )}
            <div className={styles.music_box} onClick={playOrPause} style={audioSty}>
                {isPlay ? <img className={styles.open} src="https://cp-oss.busionline.com/qzsx/music_open.png" /> : <img src="https://cp-oss.busionline.com/qzsx/music_close.png" />}
                <audio ref={audioRef} autoPlay muted src="https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效1-开场.mp3" />
            </div>
        </div>
    ) : null
})
